<!--
 * @Author: wang cong wangc9832@163.com
 * @Date: 2023-11-03 10:08:43
 * @LastEditors: wang cong wangc9832@163.com
 * @LastEditTime: 2023-11-03 13:17:38
 * @FilePath: /ams_product_front/src/components/Form/src/busComponents/InsertInput.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div style="display: flex">
    <a-input
      v-model:value="inputValue"
      @blur="isblur"
      ref="isInput"
      @change="handleChange"
    />
    <ApiSelect
      :dictCode="dictCode"
      @change="addkeyword"
      style="width: 200px"
      v-if="viewMode == 'edit'"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'InsertInput',
});
</script>
<script lang="ts" setup>
import { ref, watch } from 'vue';
import ApiSelect from '../components/ApiSelect.vue';
const props = defineProps({
  viewMode: {
    type: String,
    default: 'edit',
  },
  value: {
    type: String,
  },
  dictCode: {
    type: String,
    default: 'yes_or_no',
  },
});
const inputValue = ref();
const isInput = ref();
const dictCode = ref(props.dictCode);
function insertString(originalString, insertString, position) {
  // 将原始字符串转化为字符数组
  let originalArray = originalString?.split('') ?? [];
  // 使用splice方法在特定位置插入字符串
  originalArray.splice(position, 0, insertString);
  // 将字符数组转化回字符串
  let newString = originalArray.join('');
  return newString;
}
const index = ref();
const isblur = () => {
  index.value = isInput.value.input.selectionEnd;
};
const addkeyword = (e) => {
  inputValue.value = insertString(
    inputValue.value,
    '${' + e + '}',
    index.value
  );
  handleChange();
};
const emit = defineEmits(['change', 'update:value']);
watch(
  () => props.value,
  (val) => {
    inputValue.value = val;
  },
  { immediate: true }
);
function handleChange() {
  emit('update:value', inputValue.value);
  emit('change', inputValue.value);
}
</script>
<style lang="less" scoped></style>
